﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Global
{
    public class HighScores
    {
        public struct Data
        {
            public string name;
            public int lvl;
            public int pts;
        }
        public List<Data> scoresList = new List<Data>();
        public string path = "Content/HighScores.txt";

        //private void SaveListToFile();
        private void loadListFromFile()
        {
          // pobranie rekordow z pliku
          using( StreamReader sr = new StreamReader( path ) )
          {
            Data data = new Data();
            int i = 0;
            string s = "";
            while( (s = sr.ReadLine()) != null )
            {
              switch( i )
              {
                case 0:
                  data.name = s; break;
                case 1:
                  data.lvl = Convert.ToInt32( s ); break;
                case 2:
                  data.pts = Convert.ToInt32( s ); break;
                default:
                  break;
              }
              i++;
              if( i > 2 )
              {
                scoresList.Add( data );
                i = 0;
              }
            }
          }

        }

        public HighScores()
        {
          if( File.Exists( path ) )
          {
            loadListFromFile();

          }
          else
          {

          }
        }
        // zapis wynikow do pliku
        public void writeToFile()
        {
            int k, max;
            Data d = new Data();
	        // sortowanie od najlepszego do najgorszego wyniku
	        for(int i = 0; i < scoresList.Count() - 1; i++)
	        {
		        k = i; 
                max = scoresList[i].pts;
                d = scoresList[i];
                for (int j = i + 1; j < scoresList.Count(); j++)
		        {
                    if (scoresList[j].pts > max)
			        {
                        k = j; 
                        max = scoresList[j].pts;
                        d = scoresList[j];
			        }
		        }
                scoresList[k] = scoresList[i];
                scoresList[i] = d;
            }
            if (scoresList.Count() > 10)
                scoresList.RemoveAt(10);
            using (StreamWriter sw = File.CreateText(path))
            {
                for (int i = 0; i < scoresList.Count(); i++)
                {
                    sw.WriteLine(scoresList[i].name);
                    sw.WriteLine(scoresList[i].lvl);
                    sw.WriteLine(scoresList[i].pts);
                }
            }            
        }
    }
}
